package com.jianxin.service;

import com.jianxin.spring.BeanPostProcessor;
import com.jianxin.spring.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 模拟spring中的beanPostProcessor,可以让程序员在bean创建完成(初始化)的前/后自己自定义干预一些东西 AOP就是基于beanPostProcessor实现的
 */
@Component
public class JianxinBeanPostProcessor implements BeanPostProcessor {

    //前置方法
    @Override
    public Object postProcessBeforeInitialization(String beanName, Object bean) {
        if (beanName.equals("userService")) {
            System.out.println("userService bean beforeInitialization");
        }
        return bean;
    }

    //后置方法
    @Override
    public Object postProcessAfterInitialization(String beanName, Object bean) {
        if (beanName.equals("userService")) {
            System.out.println("userService bean afterInitialization");
            //这里就直接用jdk的动态代理了， 不考虑cglib代理的情况了
            Object instance = Proxy.newProxyInstance(JianxinBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    //代理对象的执行逻辑
                    System.out.println("调用代理对象方法 前 切面逻辑");
                    return method.invoke(bean,args);
                }
            });
            //返回代理对象
            return instance;
        }
        return bean;
    }


}
